<template>
  <div>
    <el-button type="success" @click="checkDeviceStatus">查询设备状态</el-button>
    
    <el-table :data="tableData" style="width: 100%" v-if="tableData.length">
      <el-table-column prop="token" label="Token" width="300"></el-table-column>
      <el-table-column prop="deviceSn" label="设备序列号" width="200"></el-table-column>
    </el-table>

    <p v-else>请点击按钮以查询设备状态。</p>
    
    
    <el-button type="primary" @click="checkFaceLibInfo">查询脸库信息</el-button>

    <el-table :data="faceLibTableData" style="width: 100%" v-if="faceLibTableData.length">
      <el-table-column prop="id" label="脸库 ID" width="200"></el-table-column>
      <el-table-column prop="name" label="名称" width="200"></el-table-column>
      <el-table-column prop="personNumber" label="人员数量" width="150"></el-table-column>
      <el-table-column prop="faceNumber" label="人脸特征数量" width="150"></el-table-column>
      <el-table-column prop="threshold" label="识别阈值" width="150"></el-table-column>
      <el-table-column prop="maxFaceNumber" label="最大脸容量" width="150"></el-table-column>
      <el-table-column prop="createTimestamp" label="创建时间戳" width="200"></el-table-column>
      <el-table-column prop="updateTimestamp" label="更新时间戳" width="200"></el-table-column>
    </el-table>

    <p v-else>请点击按钮以查询脸库信息。</p>

    <!-- 查询相机通道号 -->
    <el-select v-model="selectedCameraType" placeholder="请选择相机类型">
      <el-option
          v-for="item in cameraTypes"
          :key="item.value"
          :label="item.label"
          :value="item.value">
      </el-option>
    </el-select>
    <el-button type="warning" @click="queryCameraChannel">查询相机通道号</el-button>

    <el-table :data="cameraChannelTableData" style="width: 100%" v-if="cameraChannelTableData.length">
      <el-table-column prop="channelNum" label="通道号" width="150"></el-table-column>
      <el-table-column prop="available" label="是否可用" width="150"></el-table-column>
      <el-table-column prop="type" label="相机类型" width="200"></el-table-column>
      <el-table-column prop="cameraSn" label="相机 SN" width="200"></el-table-column>
    </el-table>
    <p v-else-if="cameraChannelError">{{ cameraChannelError }}</p>
    <p v-else>请点击按钮以查询相机通道号。</p>

    <el-input v-model="cameraId" placeholder="请输入相机ID（可选）" style="width: 300px; margin-right: 10px;"></el-input>
    <el-select v-model="selectedCameraTypeForList" placeholder="请选择相机类型（可选）">
      <el-option
          v-for="item in cameraTypes"
          :key="item.value"
          :label="item.label"
          :value="item.value">
      </el-option>
    </el-select>
    <el-button type="info" @click="queryCameraList">查询相机列表</el-button>

    <el-table :data="formattedCameraListTableData" style="width: 100%" v-if="formattedCameraListTableData.length">
      <el-table-column prop="id" label="相机唯一 ID" width="200"></el-table-column>
      <el-table-column prop="name" label="相机名称" width="200"></el-table-column>
      <el-table-column prop="type" label="相机类型" width="150"></el-table-column>
      <el-table-column prop="ip" label="相机地址" width="200"></el-table-column>
      <el-table-column prop="rtsp" label="RTSP 地址" width="250"></el-table-column>
      <el-table-column prop="statusMsg" label="状态" width="150"></el-table-column>
      <el-table-column prop="taskType" label="任务类型" width="150"></el-table-column>
      <el-table-column prop="taskName" label="任务名称" width="200"></el-table-column>
      <el-table-column prop="taskStatusMsg" label="任务状态" width="150"></el-table-column>
    </el-table>
    <p v-else>请点击按钮以查询相机列表。</p>
  </div>
</template>

<script>
import { fetchToken, queryDeviceStatus, queryFaceLibInfo, queryCameraChannel,queryCameraList } from '@/api/camera/tokenApi'; // 导入我们创建的 API 服务

export default {
  data() {
    return {
      tableData: [],
      faceLibTableData: [],
      cameraChannelTableData: [], // 新增：用于存储相机通道号查询的结果
      cameraListTableData: [], // 新增：存储相机列表查询的结果
      formattedCameraListTableData: [], // 新增：用于格式化后的相机列表数据
      token: null, // 用于存储获取到的 token
      selectedCameraType: 0, // 默认选择 RTSP 流相机
      cameraTypes: [
        { value: -1, label: '全部'      },
        { value: 0, label: 'RTSP 流相机' },
        { value: 1, label: '海康人脸抓拍机' },
        { value: 5, label: '小视人脸抓拍机' }
      ], // 相机类型的选项
      showCameraChannelTable: false, // 控制表格显示与否
      cameraChannelError: '', // 错误信息
      cameraId: '', // 用户填写的相机ID
      selectedCameraTypeForList: -1, // 查询相机列表时使用的相机类型，默认为全部
    };
  },
  methods: {
    async fetchToken() {
      try {
        const response = await fetchToken();
        
        // 打印整个响应对象到控制台
        console.log('API Response:', response);

        if (response.resCode === 0) {
          this.token = response.resData.token; // 存储 token
          this.tableData = [response.resData]; // 将 resData 包装成数组以便 el-table 显示
          this.$message({
            message: 'Token 获取成功',
            type: 'success'
          });
        } else {
          throw new Error('Token 获取失败');
        }
      } catch (error) {
        console.error('Error fetching token:', error);
        this.$message.error('请求出错：' + error.message);
      }
    },
    async checkDeviceStatus() {
      try {
        // 检查是否已经有 token，如果没有，则先获取 token
        if (!this.token) {
          await this.fetchToken();
        }

        // 使用获取到的 token 查询设备状态
        const response = await queryDeviceStatus(this.token);
        
        // 打印整个响应对象到控制台
        console.log('Device Status Response:', response);

        if (response.resCode === 0) {
          this.$message({
            message: '设备在线',
            type: 'success'
          });
        } else {
          this.$message.error('设备离线或查询失败');
        }
      } catch (error) {
        console.error('Error querying device status:', error);
        this.$message.error('请求出错：' + error.message);
      }
    },
    async checkFaceLibInfo() {
      try {
        // 检查是否已经有 token，如果没有，则先获取 token
        if (!this.token) {
          await this.fetchToken();
        }

        // 使用获取到的 token 查询脸库信息
        const response = await queryFaceLibInfo(this.token);

        console.log('Face Library Info Response:', response);

        if (response.resCode === 0) {
          this.faceLibTableData = response.resData.faceLibList || [];
          this.$message({
            message: '脸库信息获取成功',
            type: 'success'
          });
        } else {
          this.$message.error('脸库信息获取失败');
        }
      } catch (error) {
        console.error('Error querying face library info:', error);
        this.$message.error('请求出错：' + error.message);
      }
    },
    async queryCameraChannel() {
      try {
        if (!this.token) {
          await this.fetchToken();
        }

        const response = await queryCameraChannel(this.token, this.selectedCameraType);
        console.log('Camera Channel Query Response:', response);


        if (response.resCode === 0) {
          this.cameraChannelTableData = response.resData.channelList || [];
          this.showCameraChannelTable = true;
          this.cameraChannelError = ''; // 清除任何之前的错误信息
          this.$message({
            message: '相机通道号查询成功',
            type: 'success'
          });
        } else if (response.resCode === -1) {
          this.showCameraChannelTable = false;
          this.cameraChannelError = response.resMsg;
          this.$message.error(response.resMsg);
        }else {
          this.$message.error('相机通道号查询失败');
        }
      } catch (error) {
        console.error('Error querying camera channel:', error);
        this.$message.error('请求出错：' + error.message);
      }
    },
    async queryCameraList() {
      try {
        if (!this.token) {
          await this.fetchToken();
        }
        const response = await queryCameraList(this.token, this.selectedCameraTypeForList, this.cameraId);
        console.log('相机信息响应:', response);
        if (response.resCode === 0) {
          this.formattedCameraListTableData = [];
          (response.resData.cameraList || []).forEach(camera => {
            (camera.taskList || []).forEach(task => {
              this.formattedCameraListTableData.push({
                id: camera.id,
                name: camera.name,
                type: this.cameraTypes.find(type => type.value === camera.type)?.label || '未知',
                ip: camera.ip,
                rtsp: camera.rtsp,
                statusMsg: camera.statusMsg,
                taskType: task.taskType,
                taskName: task.taskName,
                taskStatusMsg: task.taskStatusMsg
              });
            });
          });
          this.$message({
            message: '相机信息查询成功',
            type: 'success'
          });
        } else {
          this.$message.error('相机列表查询失败');
        }
      } catch (error) {
        console.error('Error querying camera list:', error);
        this.$message.error('请求出错：' + error.message);
      }
    },
  }
};
</script>

<style scoped>

</style>